/**
 * 
 */
package com.fnic.pearl.scheduler.action;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.fnic.pearl.scheduler.dao.SchedulerStore;
import com.fnic.pearl.scheduler.mod.ProbeStatusManager;
import com.fnic.pearl.scheduler.model.ProbeLogoutReq;
import com.fnic.pearl.scheduler.model.ProbeStatus;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;


/**
 * 探针退出
 * 
 * @author HuHaiyang
 * @date 2013年10月11日
 */
public class ProbeLogoutServlet extends HttpServlet
{
    private static final long serialVersionUID = 1L;
    private static Logger LOG = Logger.getLogger(ProbeLogoutServlet.class);
    private Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
    
    /**
     * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
    	ProbeLogoutReq logoutReq = null;
    	try
    	{
    		logoutReq = gson.fromJson(new InputStreamReader(
                    request.getInputStream()), ProbeLogoutReq.class);
    	}
    	catch (Exception e)
        {
            LOG.warn("probe logout request parse exception - " + e.getMessage());
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return ;
        }
    	
    	if (logoutReq == null)
    	{
    		LOG.warn("probe logout request is null");
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return ;
    	}
    	int probeId = logoutReq.getProbeId();
        LOG.info("探针退出|" + probeId);
        if (probeId <= 0)
        {
            LOG.warn("logout: probeId = " + probeId + "|" + request.getRemoteAddr());
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return ;
        }
        
        ProbeStatus ps = ProbeStatusManager.getInstance().get(probeId);
        if (ps == null || ps.getStatus() != ProbeStatus.S_LOGIN)
        {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return ;
        }
        
        ps.setLastLogoutTime(new Date());
        ProbeStatusManager.getInstance().updateStatus(probeId, ProbeStatus.S_LOGOUT);
        
        // 更新该探针上的任务状态为 logout
        SchedulerStore.getInstance().switchLogoutTask(probeId);
        
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
    }
}
